package com.odobenus.listener;
import java.io.File;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.odobenus.zk.ZooKeeperServiceDiscovery;
@Component
public class StartListener implements ApplicationListener<ContextRefreshedEvent> {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static final String ROOT_DIR="src/main/resources/configFiles";
    @Resource
	private ZooKeeperServiceDiscovery zkDiscovery;
	
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("程序启动");
        File directory = new File(ROOT_DIR);
		// 轮询间隔 5 秒
		long interval = TimeUnit.SECONDS.toMillis(2);
		IOFileFilter filter = FileFilterUtils.or(FileFilterUtils.directoryFileFilter(), FileFilterUtils.fileFileFilter());
		// 创建一个文件观察器用于处理文件的格式
		FileAlterationObserver observer = new FileAlterationObserver(directory,filter);
		// 设置文件变化监听器
		observer.addListener(new OdobenusFileListener(ROOT_DIR,zkDiscovery));
		FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
		try {
			monitor.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

}